package com.anandsoftware.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.anandsoftware.application.ApplicationContext;
import com.anandsoftware.db.io.DatabaseIO;
import com.anandsoftware.service.BaseService;

public class BaseServiceImpl implements BaseService {

	private final Logger LOG = LoggerFactory.getLogger(BaseServiceImpl.class);

	/**
	 * 
	 * @param data
	 *            post request data in the form of key1=value1&key2=value2 ..
	 *            keyn=valuen
	 * @param requestURL
	 *            url of server page to send post request
	 * @return returns responce in the form of @String
	 * 
	 */
	public String sendPostRequest(String data, String requestURL) {

		String result = "";
		try {

			// Send the request
			URL url = new URL(requestURL);
			/* URLConnection conn = url.openConnection(); */
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			OutputStreamWriter writer = new OutputStreamWriter(
					conn.getOutputStream());

			// data=URLEncoder.encode(data, "UTF-8");
			// write parameters
			writer.write(data);
			writer.flush();
			LOG.info("Request Sent : [URL : " + requestURL + " , DATA : "
					+ data + "]");

			// Get the response
			StringBuffer answer = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				answer.append(line);
			}
			writer.close();
			reader.close();

			// Output the response
			LOG.info("Responce Received : [URL : " + requestURL + " , DATA : "
					+ answer.toString() + "]");
			result = answer.toString();

		} catch (MalformedURLException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	/**
	 * @param myID
	 *            your Application universal id (Generally CD-key)
	 * @return returns random 8 character value generated by the server in case
	 *         of successful request returns 0 or -1 in case of failure.
	 */
	@Override
	public String requestServiceAccess(String myID) {
		// TODO Auto-generated method stub
		String key = sendPostRequest(
				ApplicationContext.REQUEST_ACCESS_TOKEN + myID,
				BaseService.ACCESS_SERVICE_REQUEST_URL).trim();
		if (key.length() == ApplicationContext.KEY_LENGTH) {
			return key;
		}
		return "0";
	}

	/**
	 * @param myID
	 *            your Application universal id (Generally CD-key) Terminates
	 *            service and destroy temporary key stored on server.
	 * 
	 */
	@Override
	public void terminateService(String myID) {
		// TODO Auto-generated method stub
		sendPostRequest(ApplicationContext.TERMINATE_ACCESS_TOKEN + myID,
				BaseService.TERMINATE_SERVICE_REQUEST_URL);
	}

}
